package com.hisense.ovcloud.apicontrol.client;

import cn.hutool.json.JSONUtil;
import com.hisense.ovcloud.apicontrol.config.Constants;
import com.hisense.ovcloud.apicontrol.dto.resp.GetPlatformIdRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Component
@Slf4j
public class AppServiceClient {

    private final WebClient webClient;

    @Value("${use.default.platformid:false}")
    private boolean useDefaultPlatformId;

    @Value("${juconnect.default.platformid:5}")
    private Long JUCONNECT_PLATFORM;

    @Value("${appService.url:app-service:2181}")
    private String appServiceUrl;

    @Value("${http.timeout.seconds:5}")
    private Long TIME_OUT;

    @Value("${http.retry.times:2}")
    private Long RETRY_TIMES;

    public AppServiceClient(@Qualifier("base") WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<Long> getPlatformId(String appId) {
        if(useDefaultPlatformId){
            return Mono.just(JUCONNECT_PLATFORM);
        }
        return webClient.get()
                .uri(String.format("http://%s/appkey-platformId?appkey=%s", appServiceUrl, appId))
                .retrieve()
                .bodyToMono(GetPlatformIdRes.class)
                .retry(RETRY_TIMES)
                .doOnSuccess(res -> log.info("getPlatformId for appId {} success! res: {}", appId, JSONUtil.toJsonStr(res)))
                .doOnError(err -> log.error("getPlatformId for appId {} failed! res: {}", appId, err.getMessage()))
                .timeout(Duration.ofSeconds(TIME_OUT))
                .zipWhen(res -> {
                    if(res.getResultCode() == Constants.RESULT_CODE_SUCCESS){
                        return Mono.just(res.getPlatformId());
                    }else{
                        return Mono.just(-1L);
                    }
                }, (x, y) -> y);
    }
}

